package cn.dy.util;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class JDBCUtil {
    private  static DataSource ds;
//加载配置文件
    static {
    try {
        Properties pp =new Properties();
        InputStream is = JDBCUtil.class.getClassLoader().getResourceAsStream("druid.properties");
            pp.load(is);
            is.close();
            ds = DruidDataSourceFactory.createDataSource(pp);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
//获取链接对象
    public static Connection getconnection() throws SQLException {
        return ds.getConnection();
    }
//获取连接池
    public static DataSource getDataSource(){
        return ds;
    }

    public static void close (ResultSet res, Statement sta,Connection con){
        if (res!=null){
            try {
                res.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if (sta!=null){
            try {
                sta.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if (con!=null){
            try {
                con.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }

    public static void close ( Statement sta,Connection con){
        close(null,sta,con);
    }
}
